package com.mediacloud.app.newsmodule.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.mediacloud.app.assembly.util.FunKt;
import com.mediacloud.app.model.news.kt.TypeX;
import com.mediacloud.app.user.model.UserInfo;
import com.mediacloud.app.model.activity.BaseBackActivity;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.activity.microlive.BaseRecyclerAdapter;
import com.mediacloud.app.newsmodule.pay.BuyStatusListener;
import com.mediacloud.app.newsmodule.pay.GoldCoinPayClickListener;
import com.mediacloud.app.newsmodule.pay.MemberInfo;
import com.mediacloud.app.newsmodule.pay.MemberUtils;
import com.mediacloud.app.newsmodule.pay.VipGoods;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;

import org.json.JSONException;
import org.json.JSONObject;

public class MemberActivity extends BaseBackActivity {
    public static final int REQUEST_CODE = 12135;
    public static final String REQUEST_KEY = "buyVip";

    private ImageView imageUserIcon;
    private TextView tvNickName;
    /**
     * 昵称下面的那个描述
     * 您还未成为会员(VIP)
     */
    private TextView tvVipdes;
    /**
     * 付费续费描述
     * 会员(VIP)付费
     */
    private TextView tvBuydes;

    /**
     * 点击购买或续费
     */
    private TextView tvBuy;

    private RecyclerView listView;

    private MemberUtils memberUtils;

    private MemberInfo memberInfo;

    private ViewAdapter adapter;

    /**
     * 要购买的vip会员
     */
    private VipGoods.VipGood vipGood;

    GoldCoinPayClickListener payClickListener;
    private boolean fromUserCenter;

    @Override
    public int getLayoutResID() {
        return R.layout.activity_member;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initData();
    }

    private void initData() {
        UserInfo userInfo = UserInfo.getUserInfo(this);
        if (!userInfo.isLogin()) {
            return;
        }
        FunKt.loadRound(imageUserIcon, userInfo.getAvatar(), AppFactoryGlobalConfig.getDefaultImageLoadDrawable(), null);
      /*  GlideUtils.loadUrl(userInfo.getAvatar(), imageUserIcon, null,
                AppFactoryGlobalConfig.getDefaultImageLoadDrawable(), false, true);*/
        tvNickName.setText(userInfo.getNickname());

        memberUtils = MemberUtils.getInstance(userInfo.getUserid());
        refreshMemberInfo();
        memberUtils.getVipGoods(new MemberUtils.VipGoodsCallback() {
            @Override
            public void onSuccess(VipGoods goods) {
                adapter.setData(goods.getMeta());
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onFailed(Object obj) {

            }
        });
    }

    private void refreshMemberInfo() {
        memberUtils.getMemberInfo(new MemberUtils.MemberInfoCallback() {
            @Override
            public void onSuccess(MemberInfo memberInfo) {
                MemberActivity.this.memberInfo = memberInfo;
                if (memberInfo.getIs_vip()) {
                    tvNickName.setCompoundDrawablePadding(getResources().getDimensionPixelOffset(R.dimen.dimen3));
                    tvNickName.setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, ContextCompat.getDrawable(MemberActivity.this, R.drawable.vip_logo_mark), null);
                    tvVipdes.setText(String.format("您的会员将于%s到期", memberInfo.getVip_time_format()));
                    tvBuydes.setText(R.string.vip_contiune);
                    int stringId = R.string.renewal_immediately;
                    tvBuy.setText(String.format(getResources().getString(stringId), vipGood.getGoods_name()));
                } else {
                    tvVipdes.setText(getResources().getString(R.string.you_are_not_vip));
                    tvBuydes.setText(getResources().getString(R.string.vip_buy));
                    int stringId = R.string.renewal_immediately_buy;
                    tvBuy.setText(String.format(getResources().getString(stringId), vipGood.getGoods_name()));
                }
            }

            @Override
            public void onFailed(Object o) {

            }
        }, true);
    }

    private void initView() {
        String title = getIntent().getStringExtra("title");
        if (!TextUtils.isEmpty(title))
            setTitle(title);
        else
            setTitle(R.string.member);
        fromUserCenter = getIntent().getBooleanExtra("fromUserCenter", false);
        imageUserIcon = findViewById(R.id.image_user_icon);
        tvNickName = findViewById(R.id.tv_user_nickName);
        tvVipdes = findViewById(R.id.tv_vip_des);
        tvBuydes = findViewById(R.id.tv_buy_des);
        tvBuy = findViewById(R.id.tv_buy);
        listView = findViewById(R.id.recycler_view);
        adapter = new ViewAdapter(this);
        listView.setAdapter(adapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        listView.setLayoutManager(linearLayoutManager);
        tvBuy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (vipGood == null) {
                    return;
                }
                tvBuy.setClickable(false);
                ArticleItem articleItem = new ArticleItem();
                articleItem.setType(TypeX.OTHER.MEMBER_NONEWS);
                articleItem.setGoodsID(vipGood.getGoods_id());
                articleItem.setCps_id(vipGood.getSpu_id());
                articleItem.setPrice(vipGood.getGoods_attr_info().getPrice().getAndroid());
                payClickListener = new GoldCoinPayClickListener(articleItem, createBillSource(), new BuyStatusListener() {
                    @Override
                    public boolean onBuySuccess() {
                        tvBuy.setClickable(true);
                        Intent intent = new Intent();
                        intent.putExtra(REQUEST_KEY, true);
                        setResult(REQUEST_CODE, intent);
                        refreshMemberInfo();
                        return false;
                    }

                    @Override
                    public void onBuyFail() {
                        tvBuy.setClickable(true);
                        Intent intent = new Intent();
                        intent.putExtra(REQUEST_KEY, false);
                        setResult(REQUEST_CODE, intent);
                    }
                }, false);
                payClickListener.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        tvBuy.setClickable(true);
                    }
                });
                payClickListener.onClick(v);
            }
        });
    }

    /**
     * 创建订单bill_source
     */
    private String createBillSource() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("category", "vip");
            jsonObject.put("operation", "购买vip会员");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject.toString();
    }


    class ViewAdapter extends BaseRecyclerAdapter<VipGoods.VipGood> {
        private int selectPosition = 0;

        public ViewAdapter(Context context) {
            super(context);
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(MemberActivity.this).inflate(R.layout.vipgoods_item, null, false);
            return new VipGoodViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            if (holder instanceof VipGoodViewHolder) {
                VipGoodViewHolder vipGoodViewHolder = (VipGoodViewHolder) holder;
                vipGoodViewHolder.onBindViewHolder(getItem(position), position);
            }
        }
    }

    class VipGoodViewHolder extends RecyclerView.ViewHolder {
        private TextView tvTitle;
        private TextView tvPrice;
        private TextView tvTime;
        /**
         * 推荐
         */
        private TextView tvTuijian;

        public VipGoodViewHolder(View itemView) {
            super(itemView);
        }

        void onBindViewHolder(final VipGoods.VipGood vipGood, final int position) {
            if (position == adapter.selectPosition) {
                itemView.findViewById(R.id.item_root).setBackgroundResource(R.drawable.vipgood_item_select);
            } else {
                itemView.findViewById(R.id.item_root).setBackgroundResource(R.drawable.vipgood_item_unselect);
            }

            if (adapter.selectPosition == 0 && position == 0) {
                MemberActivity.this.vipGood = vipGood;
                int stringId = memberInfo != null && memberInfo.getIs_vip() ? R.string.renewal_immediately : R.string.renewal_immediately_buy;
                tvBuy.setText(String.format(getResources().getString(stringId), vipGood.getGoods_name()));
            }
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MemberActivity.this.vipGood = vipGood;
                    adapter.selectPosition = position;
                    adapter.notifyDataSetChanged();
                    int stringId = memberInfo != null && memberInfo.getIs_vip() ? R.string.renewal_immediately : R.string.renewal_immediately_buy;
                    tvBuy.setText(String.format(getResources().getString(stringId), vipGood.getGoods_name()));
                }
            });
            tvTitle = itemView.findViewById(R.id.tv_title);
            tvPrice = itemView.findViewById(R.id.tv_price);
            tvTime = itemView.findViewById(R.id.tv_time);
            tvTuijian = itemView.findViewById(R.id.tv_tuijian);

            tvTitle.setText(vipGood.getGoods_name());
            tvPrice.setText(String.format("￥%s", vipGood.getGoods_attr_info().getPrice().getAndroid()));
            tvTime.setText(vipGood.getGoods_desc());
        }
    }

    @Override
    protected String getContent_show_top_color() {
        if (fromUserCenter) {
            mTitileBar.setBackgroundColor(Color.WHITE);
            return "#333333";
        } else {
            return super.getContent_show_top_color();
        }
    }

    @Override
    public int getStatusBarColor() {
        if (fromUserCenter)
            return Color.WHITE;
        else return super.getStatusBarColor();
    }
}